package com.help10000.rms.mvp.presenter

import com.alibaba.fastjson.JSON
import com.amir.common.api.CustomObserver
import com.amir.common.beans.BaseResult
import com.amir.common.beans.LoginEntity
import com.amir.common.beans.SMSEntity
import com.amir.common.beans.TokenEntity
import com.amir.common.mvp.model.Model
import com.amir.common.mvp.presenter.BasePresenter
import com.amir.common.utils.Constant
import com.amir.common.utils.SPUtils
import com.amir.common.utils.ToastUtil
import com.google.gson.JsonElement
import com.help10000.rms.config.globalData
import com.help10000.rms.mvp.view.SMSView
import okhttp3.MediaType
import okhttp3.RequestBody
import java.util.UUID
import kotlin.random.Random

open class SMSPresenter(v: SMSView) : BasePresenter<SMSView>(v) {


    fun sendSms(tel: String) {
        if (tel.isBlank()) {
            ToastUtil.show("手机号不能为空")
            return;
        }
        val sendSMS = Model.getServer().sendSMS(tel)
        Model.getObservable(sendSMS, object : CustomObserver<SMSEntity>(mvpView) {

            override fun success(t: SMSEntity) {
                t.data.save();
                mvpView?.sendSmsSuccess()
            }
        })
    }

    fun checkSms(tel: String, code: String) {
        val smsId = SPUtils.getString(Constant.SmsId)
        val checkSMS = Model.getServer().checkSMS(tel, code, smsId)
        Model.getObservable(checkSMS, object : CustomObserver<BaseResult>(mvpView) {

            override fun success(t: BaseResult) {
                mvpView?.checkSMSSuccess()
            }
        })
    }

    fun loginByValidCode(tel: String, code: String , flag: Int? = 1){
        val smsId = SPUtils.getString(Constant.SmsId)
        if (tel.isEmpty()) {
            return ToastUtil.show("手机号不能为空")
        }
        if (code.isEmpty()) {
            return ToastUtil.show("验证码不能为空")
        }
        if(smsId.isNullOrEmpty()) {
            return ToastUtil.show("请先发送验证码")
        }
        val map = mutableMapOf<String, Any>()
        map["tel"] = tel
        map["verifycode"] = code
        map["smsid"] = smsId
        val body: RequestBody =
            RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                JSON.toJSON(map).toString()
            )
        val login = Model.getServer().AuthorizeByValidCode(
            returnurl = "",
            response_type = "code",
            scope = "base",
            state = "1234",
            json = body
        )

        Model.getObservable(login, object : CustomObserver<LoginEntity>(view = mvpView) {
            override fun success(t: LoginEntity) {
                if(t.msgCode == -2){
                    if(flag != 2) //如是注册后再登录，不必再调用验证码登录
                        regByValidCode(tel, code, smsId)
                }else{
                    t.save()
                    getToken(t.code)
                }
//                SPUtils.save(Constant.accoun, account)
//                SPUtils.save(Constant.pwd, psd)
//                t.save()
//                getToken(t.code)
            }
        })
    }

    fun regByValidCode(tel: String, code: String, smsId: String){
        val uuid = UUID.randomUUID().toString().split("-")[0]
        val pwd = UUID.randomUUID().toString().split("-")[0]
        val rst = Model.getServer().register(tel, "User"+uuid, pwd, smsId, code, null)
        Model.getObservable(rst, object : CustomObserver<BaseResult>(view = mvpView) {
            override fun success(t: BaseResult) {
                if (t.msgCode == 0) {
                    loginByValidCode(tel, code, 2)
                } else {
                    ToastUtil.show("登录失败")
                }
            }
        })
//        if(rest.MsgCode)
    }

    fun getToken(code: String) {
        val token = Model.getServer().getToken(code, "authorization_code")
        Model.getObservable(token, object : CustomObserver<TokenEntity>(mvpView) {

            override fun success(t: TokenEntity) {
                t.save()
                globalData.token = t
                mvpView?.loginSuccess()
            }
        })
    }
}